package com.hspedu.homework;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.Properties;

/**
 * @Author Stringzhua
 * @Date 2024/3/24 16:50
 * description:
 * 读取dog.properties文件
 * 编写dog类(name,age,color)创建dog对象,读取文件完成属性初始化,并输出
 * 将创建的Dog对象,序列化到文件dog.dat文件中
 */
public class homework03 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileReader("chapter19/src/com/hspedu/dog.properties"));
//        properties.list(System.out);
        String name = properties.getProperty("name") + "";//Object-->String
        int age = Integer.parseInt(properties.getProperty("age") + "");//Object-->int
        String color = properties.getProperty("color") + "";//Object-->String

        Dog dog = new Dog(name, age, color);
        System.out.println("=====dog对象信息=====");
        System.out.println(dog);

        //将创建的Dog对象,序列化到文件dog.dat文件中
        String serFlie = "e:\\dog.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFlie));
        oos.writeObject(dog);

        //关闭外层流
        oos.close();
        System.out.println("dog 对象序列化完成");
    }

    //编写一个方法反序列化
    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String serFliePath = "e:\\dog.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFliePath));
        Dog dog = (Dog) ois.readObject();
        System.out.println("=====反序列化后dog信息=====");
        System.out.println(dog);
        ois.close();
    }
}

class Dog implements Serializable {
    private String name;
    private int age;
    private String color;

    public Dog(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}